<template>
	<canvas canvas-id="myCanvas" :style="{width: width + 'px', height: height + 'px'}" class="my-canvas"></canvas>
</template>

<script>
	export default {
		name: 'myCanvas',
		data() {
			return {
				width: 0,
				height: 0
			}
		},
		methods: {
			urlTobase64(url, type) {
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().readFile({
						filePath: url,
						encoding: 'base64',
						success: res => {
							let base64 = res.data
							base64 = `data:image/${type};base64,${base64}`
							resolve(base64)
						}
					})
				})
			},
			// 图片分辨率压缩
			calcImageSize(res, pixels) {
				let imgW, imgH
				imgW = res.width
				imgH = res.height

				let ratio
				if ((ratio = imgW * imgH / pixels) > 1) {
					ratio = Math.sqrt(ratio)
					imgW = parseInt(imgW / ratio)
					imgH = parseInt(imgH / ratio)
				} else {
					ratio = 1
				}

				return {
					imgW,
					imgH
				}
			},
			start(imgUrl, options = {}) {
				let slef = this
				/*************** 参数默认值 ***************/
				const MAX_PIXELS = 2000000, // 最大分辨率，宽 * 高 的值
					MAX_QUALITY = 0.8, // 压缩质量
					IMG_TYPE = 'jpg',
					CANVAS_ID = 'myCanvas',
					BASE_64 = false;

				return new Promise(async (resolve, reject) => {
					uni.getImageInfo({
						src: imgUrl,
						success: res => {
							let pixels = options.pixels || MAX_PIXELS,
								quality = options.quality || MAX_QUALITY,
								type = options.type || IMG_TYPE,
								canvasId = options.canvasId || CANVAS_ID,
								isBase64 = options.base64 || BASE_64,
								{
									imgW,
									imgH
								} = this.calcImageSize(res, pixels),
								w = options.width || imgW,
								h = options.height || imgH;


							type = type == 'png' ? 'png' : 'jpg';

							console.log(`%c 宽: ${w} %c 高: ${h} %c 分辨率: ${w * h} %c 质量: ${quality} %c 类型: ${type}`, 'color:#f00',
								'background-color:#f60;color:#fff', 'color:#F00', 'background-color:#f60;color:#fff', 'color:#F00')


							slef.height = h
							slef.width = w

							slef.$nextTick(() => {
								let canvas = null
								if (!canvas) {
									canvas = uni.createCanvasContext(canvasId, slef)
								}
								canvas.drawImage(res.path, 0, 0, w, h)
								canvas.draw()
								setTimeout(() => {
									uni.canvasToTempFilePath({
										canvasId: canvasId,
										x: 0,
										y: 0,
										width: w,
										height: h,
										destWidth: w,
										destHeight: h,
										fileType: type,
										quality: quality,
										success: file => {
											if (isBase64) {
												this.urlTobase64(file.tempFilePath, type)
													.then(res => {
														canvas = null
														resolve(res)
													})
													.catch(err => {
														reject({
															code: -4,
															msg: '图片转base64错误',
															data: err
														})
													})
											} else {
												resolve(file.tempFilePath)
											}
										},
										fail: err => {
											reject({
												code: -3,
												msg: 'canvas转图片错误',
												data: err
											})
										}
									}, slef)
								}, 500)
							})
						}
					})
				})
			}
		}
	}
</script>

<style>
	.my-canvas {
		position: absolute;
		visibility: hidden;
		height: 0;
		overflow: hidden;
		left: 100000rpx;
 	}
</style>
